use std::io::Write;

fn main() {
    loop 
	{
		println!("-----------------------------------------------");
		println!("Guess the number!");
		println!("1. Start a guessing game");
		println!("2. Exit");
		print!("Please enter your choice (1 or 2): ");
		std::io::stdout().flush().expect("Failed to flush stdout");
		let mut input = String::new();
		std::io::stdin().read_line(&mut input).expect("Failed to read input");
		match input.trim() {
			"1" => {
				let secret_number = rand::random_range(1..=100);			
				println!("-----------------------------------------------");
				println!("Random number generated between 1 and 100.");
				println!("Try to guess the number!");
				let mut cnt = 7;
				println!("You have {} chances to guess the number.", cnt);
				print!("Please enter your guess: ");
				std::io::stdout().flush().expect("Failed to flush stdout");
				while cnt > 0 {
					let mut guess = String::new();
					std::io::stdin().read_line(&mut guess).expect("Failed to read input");
					match guess.trim().parse::<i32>() {
						Ok(num) => {
							if num > secret_number {
								println!("Your guess is too high.");
							} else if num < secret_number {
								println!("Your guess is too low.");
							} else {
								println!("Congratulations! You guessed the number: {}", secret_number);
								break;
							}
							cnt -= 1;
							if cnt == 0 {
								println!("Sorry, you've run out of chances. The number was: {}", secret_number);
								break;
							} else {
								println!("You have {} chances left.", cnt);
								print!("Please enter your guess: ");
								std::io::stdout().flush().expect("Failed to flush stdout");
							}
						}
						Err(_) => {
							println!("Please enter a valid number.");
							print!("Please enter your guess: ");
							std::io::stdout().flush().expect("Failed to flush stdout");
							continue;
						}
					}
				}
			}
			"2" => {
				println!("Exiting the game. Goodbye!");
				break;
			}
			_ => {
				println!("Invalid option. Please enter 1 or 2.");
				continue;
			}
		}
	}
	println!("Thank you for playing! Have a great day!");
}
